package fi.aalto.cse.T110_5150.P2PClient;

import java.util.*;

public class QueryHistory {
	
	private List<QueryInfo> queries;
	
	public QueryHistory() {
		queries = new ArrayList<QueryInfo>();
	}
	
	public QueryInfo getQuery(int messageId) {
		removeExpired();
		
		for (Iterator<QueryInfo> it = queries.iterator(); it.hasNext(); ) {
			QueryInfo query = it.next();
			
			if (query.getMessageId() == messageId) {
				return query;
			}			
		}
		
		return null;
	}
	
	public void addQuery(int messageId, ByteArray queryKey, RemotePeer sender) {
		QueryInfo query = new QueryInfo(messageId, queryKey, sender);
		queries.add(query);
	}	
	
	public boolean tryAddQuery(int messageId, ByteArray queryKey, RemotePeer sender) {
		
		QueryInfo query = getQuery(messageId);
		
		if (query == null) {
			query = new QueryInfo(messageId, queryKey, sender);
			queries.add(query);
			return true;
		} else {
			return false;
		}
		
	}
	
	private void removeExpired() {
		long currentTime = System.currentTimeMillis();
		
		synchronized (queries) {
			// clean expired queries
			while (!queries.isEmpty()) {
				QueryInfo queryInfo = queries.get(0);			
				if (queryInfo.getTime() + P2PHelper.QUERY_VALIDITY_PERIOD < currentTime) {
					queries.remove(0);
				} else {
					break;
				}
			}
		}			
	}	

}
